<?php
namespace app\admin\controller;

use think\Controller;
use think\Cache;
use think\Request;
use think\Validate;
use app\admin\model\Admin;


class Login extends Controller
{
    public function index()
    {
        if (session('admin_info')) {
            return $this->redirect('admin/index/index');
        }
        // dump(md5(sha1('123456')));exit;
        return view('index');
    }

    //登录
    public function login()
    {
        
        // return error('暂未开放登录');
        if(session('admin_info')){
            return $this->redirect('Index/index');
        }
        $request = Request::instance();

        $data = $this->request->param();
        // dd($data);
        $validate = new Validate([
            ['username', 'require|max:11|/^1[3-9]{1}[0-9]{9}$/', '请输入手机号码|手机号码最多不能超过11个字符|手机号码格式不正确'],
            ['password', 'require|length:6,18', '请输入密码|密码长度6~18个字符'],
            ['captcha', 'require|captcha', '请输入验证码|验证码不正确']
        ]);
        if (!$validate->check($data)) {
            return error($validate->getError());
        }

        $map = array(
            'username' => $data['username'],
            'password' => md5(sha1($data['password'])),
        );

        $user = Admin::where('username', $data['username'])->find();

        if(!$user){
            return error('该账户不存在!');
        }

        if($user['status'] != 1){
            return error('改账户已禁用!');
        }

        if($user['password'] != md5(sha1($data['password']))){
            return error('账户或密码错误!');
        }

        $user->ip = $request->ip();
        $user->end_time = time();
        $user->save();


        $admin_info = array(
            'id' => $user['id'],
            'username' => $user['username'],
            'nick' => $user['nick'],
            'portrait' => $user['portrait'],
            'end_time' => $user['end_time']
        );


        session('admin_info', $admin_info);
        logger(1, "管理员：".session('admin_info.username')." 登录系统");

        return success(['url'=>'/admin/index/index'], '登录成功，正在跳转中...');
    }

    public function logout()
    {
        logger(1, "管理员：".session('admin_info.username')." 退出登录");

        session('admin_info', null);

        return redirect('Login/index');
    }
}
